package com.example.demo.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.entity.User;
import com.example.demo.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserMapper userMapper;

    @GetMapping("/getUserList")
    public List query(){
        List<User> list = userMapper.selectList(null);
        return list;
    }

    @GetMapping("/findAll")
    public List<User> find(){
        return userMapper.selectAllUserAndOrders();
    }

    //    @GetMapping("/findUser")
    //    public List<User> findUser(@RequestParam Integer id) {
    //        User user = userMapper.selectUser(id); // 调用 selectUser 方法
    //        return user != null ? Collections.singletonList(user) : Collections.emptyList(); // 返回包含单个用户的列表
    //    }
    @GetMapping("/findUser")
    public List<User> findUser(@RequestParam(required = false) Integer id,
                                   @RequestParam(required = false) String username) {
            User user = userMapper.selectUser(id, username);
            return user != null ? Collections.singletonList(user) : Collections.emptyList();
    }

    @GetMapping("/users")
    public Map<String, Object> findAllUsers( //浏览器访问http://localhost:8083/user/users?username=z&page=1&size=10
            @RequestParam(required = false) String username,
            @RequestParam(required = false) String gender,
            @RequestParam(defaultValue = "1") int page,  // 默认第一页
            @RequestParam(defaultValue = "10") int size   // 默认每页 10 条记录
    ) {
        // 创建分页对象
        Page<User> userPage = new Page<>(page, size);

        // 调用 mapper 方法进行查询
        List<User> users = userMapper.selectAllUsers(userPage, username, gender);

        // 输出分页信息
        System.out.println("总记录数: " + userPage.getTotal());
        System.out.println(userPage);

        // 返回结果，包括当前页的记录和总记录数
        Map<String, Object> response = new HashMap<>();
        response.put("total", userPage.getTotal()); // 总数量
        response.put("records", users); // 当前页记录

        return response; // 返回结果
    }

}
